package com.mathlearning.auth.service;

import com.mathlearning.auth.common.BusinessException;
import com.mathlearning.auth.dto.problem.*;
import com.mathlearning.auth.entity.Problem;
import com.mathlearning.auth.repository.ProblemRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProblemAdminService {

    @Autowired
    private ProblemRepository problemRepository;

    @Transactional
    public ProblemAdminResponse createProblem(CreateProblemRequest request) {
        try {
            Problem problem = Problem.builder()
                    .courseId(request.getCourseId())
                    .chapterId(request.getChapterId())
                    .title(request.getTitle())
                    .type(request.getType())
                    .difficulty(request.getDifficulty())
                    .description(request.getDescription())
                    .inputDescription(request.getInputDescription())
                    .outputDescription(request.getOutputDescription())
                    .examples(request.getExamples() != null ? request.getExamples().toString() : null)
                    .hints(request.getHints() != null ? request.getHints().toString() : null)
                    .tags(request.getTags() != null ? request.getTags().toString() : null)
                    .options(request.getOptions() != null ? request.getOptions().toString() : null)
                    .correctAnswer(request.getCorrectAnswer())
                    .solution(request.getSolution())
                    .acceptanceRate(BigDecimal.ZERO)
                    .submitCount(0)
                    .acceptedCount(0)
                    .deleted(0)
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .build();
            
            problem = problemRepository.save(problem);
            log.info("题目创建成功，ID: {}, 标题: {}", problem.getId(), problem.getTitle());
            
            return ProblemAdminResponse.builder()
                    .id(problem.getId())
                    .courseId(problem.getCourseId())
                    .chapterId(problem.getChapterId())
                    .title(problem.getTitle())
                    .type(problem.getType())
                    .difficulty(problem.getDifficulty())
                    .acceptanceRate(problem.getAcceptanceRate())
                    .submitCount(problem.getSubmitCount())
                    .acceptedCount(problem.getAcceptedCount())
                    .deleted(problem.getDeleted())
                    .createdAt(problem.getCreatedAt())
                    .updatedAt(problem.getUpdatedAt())
                    .build();
        } catch (Exception e) {
            log.error("创建题目失败: {}", e.getMessage(), e);
            throw new BusinessException("创建题目失败: " + e.getMessage());
        }
    }

    @Transactional
    public ProblemAdminResponse updateProblem(Long problemId, UpdateProblemRequest request) {
        try {
            Problem problem = problemRepository.findById(problemId)
                    .orElseThrow(() -> new BusinessException("题目不存在"));

            // Update fields if not null
            if (request.getCourseId() != null) problem.setCourseId(request.getCourseId());
            if (request.getChapterId() != null) problem.setChapterId(request.getChapterId());
            if (request.getTitle() != null) problem.setTitle(request.getTitle());
            if (request.getType() != null) problem.setType(request.getType());
            if (request.getDifficulty() != null) problem.setDifficulty(request.getDifficulty());
            if (request.getDescription() != null) problem.setDescription(request.getDescription());
            if (request.getInputDescription() != null) problem.setInputDescription(request.getInputDescription());
            if (request.getOutputDescription() != null) problem.setOutputDescription(request.getOutputDescription());
            if (request.getExamples() != null) problem.setExamples(request.getExamples().toString());
            if (request.getHints() != null) problem.setHints(request.getHints().toString());
            if (request.getTags() != null) problem.setTags(request.getTags().toString());
            if (request.getOptions() != null) problem.setOptions(request.getOptions().toString());
            if (request.getCorrectAnswer() != null) problem.setCorrectAnswer(request.getCorrectAnswer());
            if (request.getSolution() != null) problem.setSolution(request.getSolution());
            if (request.getDeleted() != null) problem.setDeleted(request.getDeleted());

            problem.setUpdatedAt(LocalDateTime.now());
            problem = problemRepository.save(problem);
            log.info("题目更新成功，ID: {}, 标题: {}", problem.getId(), problem.getTitle());

            return ProblemAdminResponse.builder()
                    .id(problem.getId())
                    .courseId(problem.getCourseId())
                    .chapterId(problem.getChapterId())
                    .title(problem.getTitle())
                    .type(problem.getType())
                    .difficulty(problem.getDifficulty())
                    .acceptanceRate(problem.getAcceptanceRate())
                    .submitCount(problem.getSubmitCount())
                    .acceptedCount(problem.getAcceptedCount())
                    .deleted(problem.getDeleted())
                    .createdAt(problem.getCreatedAt())
                    .updatedAt(problem.getUpdatedAt())
                    .build();
        } catch (Exception e) {
            log.error("更新题目失败: {}", e.getMessage(), e);
            throw new BusinessException("更新题目失败: " + e.getMessage());
        }
    }

    @Transactional
    public void deleteProblem(Long problemId) {
        try {
            Problem problem = problemRepository.findById(problemId)
                    .orElseThrow(() -> new BusinessException("题目不存在"));
            problem.setDeleted(1); // Soft delete
            problem.setUpdatedAt(LocalDateTime.now());
            problemRepository.save(problem);
            log.info("题目删除成功，ID: {}", problemId);
        } catch (Exception e) {
            log.error("删除题目失败: {}", e.getMessage(), e);
            throw new BusinessException("删除题目失败: " + e.getMessage());
        }
    }

    public ProblemEditResponse getProblemForEdit(Long problemId) {
        try {
            Problem problem = problemRepository.findById(problemId)
                    .orElseThrow(() -> new BusinessException("题目不存在"));

            // Parse JSON strings back to lists (simplified for now)
            List<CreateProblemRequest.Example> examples = new ArrayList<>();
            List<String> hints = new ArrayList<>();
            List<String> tags = new ArrayList<>();
            List<CreateProblemRequest.Option> options = new ArrayList<>();

            return ProblemEditResponse.builder()
                    .id(problem.getId())
                    .courseId(problem.getCourseId())
                    .chapterId(problem.getChapterId())
                    .title(problem.getTitle())
                    .type(problem.getType())
                    .difficulty(problem.getDifficulty())
                    .description(problem.getDescription())
                    .inputDescription(problem.getInputDescription())
                    .outputDescription(problem.getOutputDescription())
                    .examples(examples)
                    .hints(hints)
                    .tags(tags)
                    .options(options)
                    .correctAnswer(problem.getCorrectAnswer())
                    .solution(problem.getSolution())
                    .deleted(problem.getDeleted())
                    .build();
        } catch (Exception e) {
            log.error("获取题目编辑信息失败: {}", e.getMessage(), e);
            throw new BusinessException("获取题目编辑信息失败: " + e.getMessage());
        }
    }

    @Transactional
    public BatchImportResponse batchImport(BatchImportRequest request) {
        int successCount = 0;
        List<String> failedProblems = new ArrayList<>();

        for (CreateProblemRequest problemRequest : request.getProblems()) {
            try {
                createProblem(problemRequest);
                successCount++;
            } catch (Exception e) {
                log.error("导入题目失败: {}", problemRequest.getTitle(), e);
                failedProblems.add(problemRequest.getTitle() + ": " + e.getMessage());
            }
        }
        
        return BatchImportResponse.builder()
                .successCount(successCount)
                .failureCount(failedProblems.size())
                .failedProblems(failedProblems)
                .build();
    }
}



